package net.baipeng.bp_alipay

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.annotation.NonNull
import com.alipay.sdk.app.PayTask
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

class BpAlipayPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
    companion object {
        const val TAG = "BpAlipayPlugin"
        private const val SDK_PAY_FLAG = 1
        private const val SDK_AUTH_FLAG = 2
    }

    private lateinit var channel: MethodChannel

    var activity: Activity? = null

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "bp_alipay")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            "pay" -> pay(call, result)
            "isInstalled" -> isInstalled(result)
            else -> result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {
        onDetachedFromActivity()
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        onAttachedToActivity(binding)
    }

    override fun onDetachedFromActivity() {
        activity = null
    }


    private fun pay(call: MethodCall, result: Result) {
        callback = result
        val orderInfo = call.arguments as String
        Log.d(TAG, "orderInfo: $orderInfo")
        object : Thread() {
            override fun run() {
                val alipay = PayTask(activity)
                val payResult = alipay.payV2(orderInfo, true)
                val msg = Message()
                msg.what = SDK_PAY_FLAG
                msg.obj = payResult
                mHandler.sendMessage(msg)
            }
        }.start()
    }

    private lateinit var callback: Result

    private val mHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    @Suppress("UNCHECKED_CAST") val payResult: Map<String, String> = msg.obj as Map<String, String>
                    Log.d(TAG, "payResult: $payResult")
                    callback.success(payResult.plus("platform" to "android"))
                }
                SDK_AUTH_FLAG -> {
                }
                else -> {
                }
            }
        }
    }

    private fun isInstalled(result: Result) {
        val manager = activity?.packageManager
        if (manager != null) {
            val action = Intent(Intent.ACTION_VIEW)
            action.data = Uri.parse("alipays://")
            val list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER)
            result.success(list.isNotEmpty())
        } else {
            result.error("-1", "can't find packageManager", null)
        }
    }

}
